package com.sh.shanhuo.listener;


import android.os.Handler;
import android.util.Log;

import com.google.gson.Gson;
import com.sh.shanhuo.utils.OkHttpUtil;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import okhttp3.ResponseBody;

public abstract class GsonObjectCallback<T> implements Callback {

    private final Handler handler = OkHttpUtil.getInstance().getHandler();


    //主线程处理
    public abstract void onUi(T t);

    //主线程处理
    public abstract void onFailed(Call call, IOException e);

    //请求失败
    @Override
    public void onFailure(@NotNull Call call, final IOException e) {
        handler.post(() -> { //java.net.ConnectException: Failed to connect to /54.68.159.34:80
            onFailed(call, e);
        });
    }

    //请求json 并直接返回泛型的对象 主线程处理
    @SuppressWarnings("rawtypes")
    @Override
    public void onResponse(@NotNull Call call, Response response) throws IOException {
        try {
            ResponseBody responseBody = response.peekBody(1024 * 1024);
            Log.e("HTTP", String.format("接收响应: [%s] %n 返回json:【%s】 %.1fms %n %s",
                    response.request().url(),
                    responseBody.string(),
                    0.0,
                    response.headers()));
            final String json = response.body().string();
            if (200 == response.code()){
                Class<T> cls = null;
                //Type cls = null;
                Class clz = this.getClass();
                ParameterizedType type = (ParameterizedType) clz.getGenericSuperclass();
                Type[] types = new Type[0];
                if (type != null) {
                    types = type.getActualTypeArguments();
                }
                cls = (Class<T>) types[0];
                Gson gson = new Gson();
                final T t = gson.fromJson(json, cls);
                handler.post(() -> onUi(t));
            } else {
                handler.post(() -> onFailed(call, new IOException()));
            }
        }catch (IllegalStateException e){
           // Log.e("IOTCamera", "请求事件视频出错：" + e.toString());
            e.getStackTrace();
        }
    }
}
